package top.asteam.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import top.asteam.springcloud.entity.CommonResult;
import top.asteam.springcloud.entity.Payment;
import top.asteam.springcloud.lb.LoadBalancer;

import java.net.URI;
import java.util.List;

/**
 * @Author Rock Wang
 * @Time 2021/4/11
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    //    public static final String PAYMENT_URL="http://localhost:8001/data";
    public static final String PAYMENT_URL = "http://cloud-payment-service/data";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancer loadBalancer;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/payment/lb")
    public String lb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        ServiceInstance instance = loadBalancer.instance(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/data/payment/lb", String.class);
    }

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/save", payment, CommonResult.class);
    }

    @GetMapping("/payment/get")
    public CommonResult<Payment> getPaymentById(@RequestParam Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/getById?id=" + id, CommonResult.class);
    }

    @GetMapping("/getAll")
    public CommonResult getAll() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/getAll", CommonResult.class);
    }

    @GetMapping("/payment/getForEntity")
    public CommonResult<Payment> getPaymentById2(@RequestParam Long id) {
        ResponseEntity<CommonResult> entity =
                restTemplate.getForEntity(PAYMENT_URL + "/payment/getById?id=" + id, CommonResult.class);

        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new CommonResult<>(401, "操作失败", false);
        }

    }

    // ====================> zipkin+sleuth
    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin()
    {
        String result = restTemplate.getForObject("http://localhost:8001"+"/data/payment/zipkin/", String.class);
        return result;
    }
}
